import { createPinia, defineStore } from "pinia";
import piniaPluginPersistedstate from "pinia-plugin-persistedstate";
import SecureLS from "secure-ls";
import { appLogin, getSystemMemberInfo } from "@/api/api";
import { navigateTo } from "@/router/index";
import { Toast } from 'vant'
import { isWeChatBrowser } from '@/utils/util'
const ls = new SecureLS({
    // encodingType: "aes", // 加密方式
    isCompression: false, // 是否启用数据压缩
    encryptionSecret: "cb086140-3408-4d14-bfcc-5776de8f91ca",
});
const st = {
    setItem: (key, value) => ls.set(key, value),
    getItem: (key) => ls.get(key),
    removeItem: (key) => ls.remove(key),
};

const useAppStore = defineStore({
    id: "app",
    state: () => ({
        token: "",
        spinning: false,
        userInfo: {},
        avatar: "",
        username: ''
    }),
    actions: {
        setToken(v) {
            this.token = v;
        },
        setSpinning(v) {
            this.spinning = v;
        },
        async logout() {
            if (isWeChatBrowser()) { // 微信中打开
                navigateTo("/vip")
            } else { // 普通浏览器中打开
                navigateTo("/login")
            }
        },
        async login(v) {
            const res = await appLogin(v);
            if (res.code == '200') {
                let token = 'Bearer ' + res.token;
                localStorage.setItem("token", token);
                if (res.memberId) {
                    this.getUserInfo(res.memberId);
                } else {
                    navigateTo("/vip")
                }
            } else {
                Toast.fail(res.msg)
                return;
            }
        },
        async getUserInfo(c) {
            getSystemMemberInfo(c).then((res) => {
                if (res.code == '200') {
                    localStorage.setItem("userInfo", JSON.stringify(res.data));
                    navigateTo("/vip")
                }
            });
        }
    },
    persist: {
        paths: ["token"],
        storage: st,
    },
});

const pinia = createPinia();
pinia.use(piniaPluginPersistedstate);

export { useAppStore, pinia };